package server.views.servermngpanel.toppanel;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import sjtu.DCL.GM.common.Goods;
import sjtu.DCL.GM.common.Message;
import sjtu.DCL.GM.server.Public;
import sjtu.DCL.GM.server.ServerMain;
import sjtu.DCL.GM.server.dao.DaoFactory;
import sjtu.DCL.GM.server.dao.GoodsDao;
import sjtu.DCL.GM.server.dao.UserDao;

/**
 * 
 * @author solomon
 *
 */

public class ReceiveThread implements Runnable {
	private String id;

	private ObjectInputStream ois;

	private boolean stop = false;

	private Message dataPacket = null;
	
	private ServerMain f;
	private UserDao userDao=DaoFactory.newInstance().createUserDao();
	private GoodsDao goodsDao=DaoFactory.newInstance().createGoodsDao();
	private HashMap h=new HashMap();
	
	public ReceiveThread(String id, ObjectInputStream ois, ServerMain f) {
		this.id = id;
		this.ois = ois;
		this.f = f;
	}

	public void run() {
		while (!stop) {		
			try {
				dataPacket = (Message) ois.readObject();

				if (dataPacket.getType().equals(Message.down_line_type)) {
					// 如果是下线包的话,向所有用户发下线包
					sendDownLinePacket();
					TopPanel.setTShow(dataPacket.getFrom(),5);
					break;
				} 				
				else if(dataPacket.getType().equals(Message.UPDATE_PWD)){
					//密码修改包
					String QQ_id =dataPacket.getFrom();
					String QQ_pwd=(String) dataPacket.getData().get("newPwd");//新密码
					//根据QQ_id到存储介质中修改用户的密码
					userDao.updatePwd(QQ_id, QQ_pwd);
					
				}else if(dataPacket.getType().equals(Message.update_tree_type)){
					//更新树
					sendUpdateTreePacket();
				}

				
				/**
				 * 修改商品
				 */
				
				else if(dataPacket.getType().equals(Message.edit_goods_type)){

					String QQ_id =dataPacket.getFrom();
					
					//Goods goods = (Goods) dataPacket.getData().get("data");
					ArrayList AL = (ArrayList)dataPacket.getData().get("data");
					
					Goods goods =(Goods)AL.get(0);
					
					System.out.println("ID:  "+goods.getId());
					System.out.println("Comments:  "+goods.getComments());
					System.out.println("Name:  "+goods.getName());
					System.out.println("Factory:  "+goods.getFactory());
					System.out.println("Category:  "+goods.getCategory());
					System.out.println("Price:  "+goods.getPrice());
					
					int result = goodsDao.updateGoods(goods);
					System.out.println(result);
					
					if(result == 1){
						
						//修改成功，返回列表
						String fromId = dataPacket.getFrom();
						
						HashMap h = new HashMap();
						h.put("1", "");
						Vector vDept = goodsDao.selectGoods(h);
						ArrayList data = new ArrayList();
						data.add(vDept);
						HashMap tempData = new HashMap();
						
						tempData.put("data", data);
						
						//通知其他在线者 更新的列表
						Message tempDataPacket = new Message(Message.ValiDate_type,"","",tempData);
						Set set = (Set) Public.mySocketInfo.keySet();//取出所有id
						Iterator iter = set.iterator();
						while(iter.hasNext()){
							String userId=(String) iter.next();
							ArrayList al=(ArrayList) Public.mySocketInfo.get(userId);
							ObjectOutputStream oos=(ObjectOutputStream) al.get(2);
							try {
								oos.writeObject(tempDataPacket);
							} catch (IOException e1) {
								e1.printStackTrace();
							}
							try {
								oos.flush();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
						

					}else {
						//添加失败，返回失败
						String fromId = dataPacket.getFrom();
						ObjectOutputStream oos = (ObjectOutputStream) ((ArrayList) Public.mySocketInfo
								.get(fromId)).get(2);						
						
						Message resultPacket = null;
						HashMap data = new HashMap();

						data.put("data", "修改商品失败");

						//只通知 fromId结果消息
						resultPacket = new Message(Message.fail_to_edit_goods_type, Message.Server_Id,
								fromId, data);						
						oos.writeObject(resultPacket);
						oos.flush();
					}
				}
				
				/**
				 * 增加商品
				 */
				
				else if(dataPacket.getType().equals(Message.add_goods_type)){

					String QQ_id =dataPacket.getFrom();
					
					ArrayList AL = (ArrayList)dataPacket.getData().get("data");
					
					Goods goods =(Goods)AL.get(0);
					//Goods goods = (Goods) dataPacket.getData().get("data");

					int result = goodsDao.addGoods(goods);
					if(result == 1){
					//增加成功，返回列表
						String fromId = dataPacket.getFrom();
						ObjectOutputStream oos = (ObjectOutputStream) ((ArrayList) Public.mySocketInfo
								.get(fromId)).get(2);
									
						HashMap h = new HashMap();
						h.put("1", "");
						Vector vDept = goodsDao.selectGoods(h);
						ArrayList data = new ArrayList();
						data.add(vDept);
						HashMap tempData = new HashMap();
						
						tempData.put("data", data);
						
										
					    //通知其他在线者 更新的列表
						Message tempDataPacket = new Message(Message.ValiDate_type,"","",tempData);
						Set set = (Set) Public.mySocketInfo.keySet();//取出所有id
						Iterator iter = set.iterator();
						while(iter.hasNext()){
							String userId=(String) iter.next();
							ArrayList al=(ArrayList) Public.mySocketInfo.get(userId);
							oos=(ObjectOutputStream) al.get(2);
							try {
								oos.writeObject(tempDataPacket);
							} catch (IOException e1) {
								e1.printStackTrace();
							}
							try {
								oos.flush();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
						

					}else {
						//添加失败，返回失败
						String fromId = dataPacket.getFrom();
						ObjectOutputStream oos = (ObjectOutputStream) ((ArrayList) Public.mySocketInfo
								.get(fromId)).get(2);						
						
						Message resultPacket = null;
						HashMap data = new HashMap();

						data.put("data", "增加商品失败");

						resultPacket = new Message(Message.fail_to_add_goods_type, Message.Server_Id,
								fromId, data);						
						oos.writeObject(resultPacket);
						oos.flush();
					}
				}
				
				/**
				 * 删除商品
				 */
				
				else if(dataPacket.getType().equals(Message.delete_goods_type)){

					String QQ_id =dataPacket.getFrom();
					
					ArrayList AL = (ArrayList)dataPacket.getData().get("data");
					
					Goods goods =(Goods)AL.get(0);
					
					//Goods goods = (Goods) dataPacket.getData().get("data");

					int result = goodsDao.deleteGoods(goods.getId());
					if(result == 1){
					//删除成功，返回列表
						String fromId = dataPacket.getFrom();
						ObjectOutputStream oos = (ObjectOutputStream) ((ArrayList) Public.mySocketInfo
								.get(fromId)).get(2);
									
						HashMap h = new HashMap();
						h.put("1", "");
						Vector vDept = goodsDao.selectGoods(h);
						ArrayList data = new ArrayList();
						data.add(vDept);
						HashMap tempData = new HashMap();
						
						tempData.put("data", data);
						
												
						
					    //通知其他在线者 更新的列表
						Message tempDataPacket = new Message(Message.ValiDate_type,"","",tempData);
						Set set = (Set) Public.mySocketInfo.keySet();//取出所有id
						Iterator iter = set.iterator();
						while(iter.hasNext()){
							String userId=(String) iter.next();
							ArrayList al=(ArrayList) Public.mySocketInfo.get(userId);
							oos=(ObjectOutputStream) al.get(2);
							try {
								oos.writeObject(tempDataPacket);
							} catch (IOException e1) {
								e1.printStackTrace();
							}
							try {
								oos.flush();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}

					}else {
						//删除失败，返回失败
						String fromId = dataPacket.getFrom();
						ObjectOutputStream oos = (ObjectOutputStream) ((ArrayList) Public.mySocketInfo
								.get(fromId)).get(2);						
						
						Message resultPacket = null;
						HashMap data = new HashMap();

						data.put("data", "删除商品失败");

						resultPacket = new Message(Message.fail_to_delete_goods_type, Message.Server_Id,
								fromId, data);						
						oos.writeObject(resultPacket);
						oos.flush();
					}
				}
				
	
				
			} catch (SocketException e) {
				// 向所有用户发下线包
				sendDownLinePacket();
				return;
			} catch (IOException e) {
				return;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				return;
			}
		}
	}

	public void sendDownLinePacket() {
		Set set = (Set) Public.mySocketInfo.keySet();
		Iterator iter = set.iterator();
		String[] QQ_id = new String[set.size()];
		int i = 0;
		//System.out.println(set.size());
		while (iter.hasNext()) {
			QQ_id[i] = (String) iter.next();
			//System.out.println(QQ_id[i]);
			if (!QQ_id[i].equals(id)) {
				ArrayList arry = (ArrayList) Public.mySocketInfo.get(QQ_id[i]);
				ObjectOutputStream tempOos = (ObjectOutputStream) arry.get(2);// 取出list里的输出流
				Message downLinePacket = new Message(
						Message.down_line_type, id, QQ_id[i], null);
				if (downLinePacket != null) {
					try {
						// 发出下线包
						tempOos.writeObject(downLinePacket);
						tempOos.flush();
					} catch (IOException e) {
						return;
					}
				}
			}
			i++;
		}
		Public.mySocketInfo.remove(id);
		// 修改数据库的用户表的用户在线字段改成0
		userDao.updateOnLine(0, id);
		// 刷新在线用户的显示
		h.put("9", "");
		Vector vector = userDao.selectUser(h);
		h.clear();
		f.getServerMngPanel().getTablePanel().getDataModel().setData(vector);
	}
	
	public void sendUpdateTreePacket() {
		Set set = (Set) Public.mySocketInfo.keySet();
		Iterator iter = set.iterator();
		String[] QQ_id = new String[set.size()];
		int i = 0;
		//System.out.println(set.size());
		while (iter.hasNext()) {
			QQ_id[i] = (String) iter.next();
			//System.out.println(QQ_id[i]);
			if (!QQ_id[i].equals(id)) {
				ArrayList arry = (ArrayList) Public.mySocketInfo.get(QQ_id[i]);
				ObjectOutputStream tempOos = (ObjectOutputStream) arry.get(2);// 取出list里的输出流
				Message updateTreePacket = new Message(
						Message.update_tree_type, id, "", null);
				if (updateTreePacket != null) {
					try {
						// 发出下线包
						tempOos.writeObject(updateTreePacket);
						tempOos.flush();
					} catch (IOException e) {
						return;
					}
				}
			}
			i++;
		}
//		Public.mySocketInfo.remove(id);
//		// 修改数据库的用户表的用户在线字段改成0
//		userDao.updateOnLine(0, id);
		// 刷新在线用户的显示
		h.put("9", "");
		Vector vector = userDao.selectUser(h);
		h.clear();
		f.getServerMngPanel().getTablePanel().getDataModel().setData(vector);
	}
	
}
